package team.knowers.qzhserver.access.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import team.knowers.qzhserver.common.api.CommonResult;
import team.knowers.qzhserver.user.user.entity.dao.UserDO;
import team.knowers.qzhserver.user.user.entity.dto.UserLoginParamDTO;
import team.knowers.qzhserver.user.user.entity.dto.UserRegisterParamDTO;
import team.knowers.qzhserver.user.user.service.UserService;
import team.knowers.qzhserver.user.user.service.impl.UserServiceImpl;
import team.knowers.qzhserver.user.userData.entity.dao.UserDataDO;


import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录注册管理Controller
 *
 * @author xtg
 * @date 2024/2/11 21:37
 */
@Controller
@Tag(name = "UserAccessController", description = "用户登录和注册")
@RequestMapping("/access")
public class UserAccessController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    private final Logger logger = LoggerFactory.getLogger(UserAccessController.class);
    @Autowired
    private UserServiceImpl userService;

    @Operation(summary = "用户登录，并返回token")
    @PostMapping("/login")
    @ResponseBody
    public CommonResult login(@Validated @RequestBody UserLoginParamDTO userLoginParamDTO) {
        String token = userService.login(userLoginParamDTO.getUsername(), userLoginParamDTO.getPassword());
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap, "登录成功");
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    @ResponseBody
    public CommonResult register(@RequestBody UserRegisterParamDTO userRegisterParamDTO) throws Exception {
//        return CommonResult.success("success");
        UserDO userDO = userService.register(userRegisterParamDTO);
        if (userDO == null) {
            return CommonResult.failed("用户名已存在");
        }
        return CommonResult.success(userDO, "注册成功");
    }

    @Operation(summary = "用户登出")
    @PostMapping("/logout")
    @ResponseBody
    public CommonResult logout() {
        return CommonResult.success(null);
    }
}
